const MAX_POST_LENGTH = 1024000;//最大接收数据量（字节）

var fs = require('fs');  
function start(ip,port,consts){
	
	process.env.TZ = "Asia/Shanghai";
	const consts_modeule = require('../../consts/');
	const consts_val = consts_modeule.select(consts);
	global.consts=consts_val;
	const http = require('http');//引入系统http模块

    const controller = require('./controller');
    
	const JQTableIF =require('../../db');
	
	const JQService =require('./service');
	const JQMysqlConnection =require('../../basic/mysql_connection');
	const JQResponse = require('../../basic/response');
	const JQRequest = require('../../basic/request');
    const JQHttpContent = require('../../basic/http_content');
	const JQNetwork = require('../../network');
	const JQGuid = require('../../utils/guid.js');
	const JQNormal = require('../../utils/normalobject.js');
	const JQSqlBaseIf = require('./batis/sql_base.js');

	global.JQTableIF = JQTableIF;
	global.JQService = JQService;
	global.JQMysqlConnection =JQMysqlConnection;
	global.JQResponse =JQResponse;
	global.JQRequest = JQRequest;
	global.JQBaseController = controller;
	global.JQHttpContent = JQHttpContent;
	global.JQNetwork = JQNetwork;
	global.JQGuid = JQGuid;
	global.JQNormal = JQNormal;
	global.JQSqlBaseIF = JQSqlBaseIf;
	console.log(global.JQSqlBaseIF);
	
	// var service = require('./router/service');//引入router模块的service
	http.createServer(function handler(req, res) {
		var data=''; //客户端每一次请求时候初始化data
		if(req.method.toUpperCase()==='POST'){
	         //data事件添加接收到的chunk到data尾部
			req.on('data', function(chunk) {
				data+=chunk;
				//针对协议的数据不会太长，如果太长数据没有接收完成则是有问题的数据，终止接收
				if(data.length>MAX_POST_LENGTH){
					
					//停止连接
					req.connection.pause();
					req.connection.end();//调用end终止请求返回给终端

				}
				
			});
		    //end事件是数据完成时候的回调
			req.on('end', function() {
				console.log(JSON.stringify(req.headers));
				console.log("end ok");
			
				//通过service的router入口，得到业务的回应数据
	    	    global.JQBaseController.router(req.url, data,function(result){
//	    	    	设置http Header 为跨域名访问
	    	    	res.writeHead(200, {'Content-Type': 'application/json',
	    	    		'Access-Control-Allow-Methods':'GET,POST','Access-Control-Allow-Origin':'*'});

	    	    	res.write(result);
	    	    	res.end();
	    	    });
	    
			});
			
		}else if(req.method.toUpperCase()==='GET'){//对于GET请求，服务器不做处理，因为协议不支持GET
			//简单的设置http Header
			res.writeHead(200, {'Content-Type': 'text/plain'});
			//返回简单的欢迎语
			res.end('Welcome jqepay smm');
			//res.end('Hello GET Xuzuotao:' + Math.floor(Math.random()*2)+'\n' + ' '+ Math.floor(2.9)+'\n');
		
		}
       console.log('req::' +req.url);
	}).listen(port); //开始监听端口
	console.log('Server running at port:'+port);
			
}
module.exports.start=start;
	